import sys
import os
import subprocess

def run_command(command, cwd=None):
    """
    运行shell命令并打印输出
    """
    result = subprocess.run(command, shell=True, cwd=cwd,text=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE,encoding='utf-8')
    if result.returncode != 0:
        print(f"{command}: error")
        print(f"result.stderr:{result.stderr}")
        sys.exit(-1)

    return result


def push_to_git_repo(folder_path, remote_branch, local_branch=None):
    # 检查文件夹路径是否存在
    if not os.path.isdir(folder_path):
        print(f"Error: The folder path '{folder_path}' does not exist.")
        return

    # 切换到指定的目录
    os.chdir(folder_path)

    # 检查是否是一个git仓库
    if not os.path.exists(os.path.join(folder_path, ".git")):
        print(f"Error: The folder path '{folder_path}' is not a git repository.")
        return

    # 添加所有文件到 Git
    run_command(["git", "add", "."],cwd=folder_path)
    run_command(["git", "fetch"],cwd=folder_path)
    result=run_command(["git", "status"],cwd=folder_path)
 
    if 'nothing to commit, working tree clean' not in result.stdout:
        run_command(["git", "commit", "-m", "Commit changes before push"],cwd=folder_path)
    else:
        print("donot need commit")
    result=run_command(["git", "status"],cwd=folder_path)
    if 'use "git push" to publish your local commits'  in result.stdout:
        run_command(["git", "push", "origin", f"{remote_branch}"],cwd=folder_path)
        print("Push successful.")
    else:
        print("donot need Push")

if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python git_push.py <folder_path> <remote_branch> ")
    else:
        current_directory = os.getcwd()
        folder_path = os.path.join(current_directory, sys.argv[1])
        remote_branch = sys.argv[2]

        push_to_git_repo(folder_path, remote_branch)


